package com.dustedpixels.commons.search.util;

import com.dustedpixels.commons.search.Finder;
import com.dustedpixels.commons.search.implbase.FinderImplBase;

/**
 * Wrapping Finder limiting number of results retrieved from underlying Finder.
 * 
 * @param <T>
 */
public final class LimitingFinder<T> extends FinderImplBase<T> {
    private final Finder<T> underlyingFinder;
    private final int limit;
    private int resultsCount;
    
    /**
     * Wraps underlying finder limiting number of retrieved results.
     * 
     * @param underlyingFinder The underlying finder.
     * @param limit The results limit.
     */
    public LimitingFinder(Finder<T> underlyingFinder, int limit) {
        this.underlyingFinder = underlyingFinder;
        this.limit = limit;
    }
    
    public void beginSearch(String query) {
        underlyingFinder.beginSearch(query);
        resultsCount = 0;
    }

    public void endSearch() {
        underlyingFinder.endSearch();
    }

    public T getNextResult() {
        T result = null;
        
        if (resultsCount < limit) {
            result = underlyingFinder.getNextResult();
            
            resultsCount++;
        }
        
        return result;
    }
    
    public boolean isNextResultImmediate() {
        return (resultsCount >= limit) || 
                underlyingFinder.isNextResultImmediate();
    }

    public boolean isRunning() {
        return underlyingFinder.isRunning();
    }
}
